/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package customers;

import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Aggelos
 */
public class NewMasterDetailForm extends JPanel {
    
    public NewMasterDetailForm() {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("TelePassPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Customer c");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        detailScrollPane = new javax.swing.JScrollPane();
        detailTable = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        newDetailButton = new javax.swing.JButton();
        deleteDetailButton = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        newDetailButton1 = new javax.swing.JButton();
        deleteDetailButton1 = new javax.swing.JButton();
        refreshButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jLayeredPane8 = new javax.swing.JLayeredPane();
        jLabel6 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel24 = new javax.swing.JLabel();
        jSeparator3 = new javax.swing.JSeparator();

        FormListener formListener = new FormListener();

        setMinimumSize(new java.awt.Dimension(800, 600));
        setPreferredSize(new java.awt.Dimension(740, 600));
        setLayout(null);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${FName}"));
        columnBinding.setColumnName("FName");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${LName}"));
        columnBinding.setColumnName("LName");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Address");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${zipCode}"));
        columnBinding.setColumnName("Zip Code");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${city}"));
        columnBinding.setColumnName("City");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
        columnBinding.setColumnName("Phone");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${email}"));
        columnBinding.setColumnName("Email");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${adt}"));
        columnBinding.setColumnName("Adt");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${afm}"));
        columnBinding.setColumnName("Afm");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterScrollPane.setViewportView(masterTable);

        add(masterScrollPane);
        masterScrollPane.setBounds(10, 230, 549, 150);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${selectedElement.vehicleList}");
        jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, eLProperty, detailTable);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${regNumber}"));
        columnBinding.setColumnName("Reg Number");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${colour}"));
        columnBinding.setColumnName("Colour");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${factoryName}"));
        columnBinding.setColumnName("Factory Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${modelType}"));
        columnBinding.setColumnName("Model Type");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${categoryId}"));
        columnBinding.setColumnName("Category Id");
        columnBinding.setColumnClass(model.VehicleCategory.class);
        jTableBinding.setSourceUnreadableValue(java.util.Collections.emptyList());
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        detailScrollPane.setViewportView(detailTable);

        add(detailScrollPane);
        detailScrollPane.setBounds(10, 421, 549, 160);

        jPanel1.setBackground(new java.awt.Color(255, 102, 102));

        newDetailButton.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        newDetailButton.setForeground(new java.awt.Color(102, 0, 153));
        newDetailButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newDetailButton.setText("ΝΕΟ");
        newDetailButton.setActionCommand("ΝΕΟ");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), newDetailButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        newDetailButton.addActionListener(formListener);
        jPanel1.add(newDetailButton);

        deleteDetailButton.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        deleteDetailButton.setForeground(new java.awt.Color(102, 0, 153));
        deleteDetailButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteDetailButton.setText("ΔΙΑΓΡΑΦΗ");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, detailTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), deleteDetailButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        deleteDetailButton.addActionListener(formListener);
        jPanel1.add(deleteDetailButton);

        jButton4.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        jButton4.setForeground(new java.awt.Color(102, 0, 153));
        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton4.setText("ΑΚΥΡΟ");
        jButton4.addActionListener(formListener);
        jPanel1.add(jButton4);

        add(jPanel1);
        jPanel1.setBounds(580, 260, 140, 100);

        jPanel2.setBackground(new java.awt.Color(255, 102, 102));

        newDetailButton1.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        newDetailButton1.setForeground(new java.awt.Color(102, 0, 153));
        newDetailButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newDetailButton1.setText("ΝΕΟ");
        newDetailButton1.addActionListener(formListener);
        jPanel2.add(newDetailButton1);

        deleteDetailButton1.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        deleteDetailButton1.setForeground(new java.awt.Color(102, 0, 153));
        deleteDetailButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteDetailButton1.setText("ΔΙΑΓΡΑΦΗ");
        deleteDetailButton1.addActionListener(formListener);
        jPanel2.add(deleteDetailButton1);

        refreshButton1.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        refreshButton1.setForeground(new java.awt.Color(102, 0, 153));
        refreshButton1.setText("ΑΝΑΝΕΩΣΗ");
        refreshButton1.addActionListener(formListener);
        jPanel2.add(refreshButton1);

        jButton6.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        jButton6.setForeground(new java.awt.Color(102, 0, 153));
        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jButton6.setText("ΑΠΟΘΗΚΕΥΣΗ");
        jButton6.addActionListener(formListener);
        jPanel2.add(jButton6);

        jButton7.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        jButton7.setForeground(new java.awt.Color(102, 0, 153));
        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton7.setText("ΑΚΥΡΟ");
        jButton7.addActionListener(formListener);
        jPanel2.add(jButton7);

        add(jPanel2);
        jPanel2.setBounds(580, 420, 140, 160);

        jLayeredPane8.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(153, 0, 0), null));
        jLayeredPane8.setToolTipText("");

        jLabel6.setFont(new java.awt.Font("Verdana", 0, 36)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(102, 0, 153));
        jLabel6.setText("Tele-Pass");
        jLabel6.setBounds(240, 30, 180, 40);
        jLayeredPane8.add(jLabel6, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/toll_image1.jpg"))); // NOI18N
        jLabel4.setToolTipText("");
        jLabel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jLabel4.setBounds(0, 0, 180, 100);
        jLayeredPane8.add(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel23.setFont(new java.awt.Font("Lucida Sans", 0, 14)); // NOI18N
        jLabel23.setForeground(new java.awt.Color(102, 0, 153));
        jLabel23.setText("Automatic Toll Collection System");
        jLabel23.setBounds(240, 70, 230, 30);
        jLayeredPane8.add(jLabel23, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel5.setFont(new java.awt.Font("Bradley Hand ITC", 0, 10)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(102, 0, 153));
        jLabel5.setText("Developed by ANDIMAGI workgroup");
        jLabel5.setBounds(570, 10, 180, 20);
        jLayeredPane8.add(jLabel5, javax.swing.JLayeredPane.DEFAULT_LAYER);

        add(jLayeredPane8);
        jLayeredPane8.setBounds(0, 0, 740, 100);

        jSeparator2.setForeground(new java.awt.Color(102, 0, 153));
        add(jSeparator2);
        jSeparator2.setBounds(10, 400, 710, 10);

        jLabel24.setFont(new java.awt.Font("Lucida Sans", 1, 18)); // NOI18N
        jLabel24.setForeground(new java.awt.Color(102, 0, 153));
        jLabel24.setText("Επεξεργασία Στοιχείων");
        add(jLabel24);
        jLabel24.setBounds(230, 140, 240, 30);

        jSeparator3.setForeground(new java.awt.Color(102, 0, 153));
        add(jSeparator3);
        jSeparator3.setBounds(10, 190, 710, 10);

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == deleteDetailButton) {
                NewMasterDetailForm.this.deleteDetailButtonActionPerformed(evt);
            }
            else if (evt.getSource() == newDetailButton) {
                NewMasterDetailForm.this.newDetailButtonActionPerformed(evt);
            }
            else if (evt.getSource() == jButton4) {
                NewMasterDetailForm.this.jButton4ActionPerformed(evt);
            }
            else if (evt.getSource() == newDetailButton1) {
                NewMasterDetailForm.this.newDetailButton1ActionPerformed(evt);
            }
            else if (evt.getSource() == deleteDetailButton1) {
                NewMasterDetailForm.this.deleteDetailButton1ActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton1) {
                NewMasterDetailForm.this.refreshButton1ActionPerformed(evt);
            }
            else if (evt.getSource() == jButton6) {
                NewMasterDetailForm.this.jButton6ActionPerformed(evt);
            }
            else if (evt.getSource() == jButton7) {
                NewMasterDetailForm.this.jButton7ActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    
    private void deleteDetailButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteDetailButtonActionPerformed
        int index = masterTable.getSelectedRow();
        model.Customer c = list.get(masterTable.convertRowIndexToModel(index));
        Collection<model.Vehicle> vs = c.getVehicleList();
        int[] selected = detailTable.getSelectedRows();
        List<model.Vehicle> toRemove = new ArrayList<model.Vehicle>(selected.length);
        for (int idx = 0; idx < selected.length; idx++) {
            selected[idx] = detailTable.convertRowIndexToModel(selected[idx]);
            int count = 0;
            Iterator<model.Vehicle> iter = vs.iterator();
            while (count++ < selected[idx]) {
                iter.next();
            }
            model.Vehicle v = iter.next();
            toRemove.add(v);
            entityManager.remove(v);
        }
        vs.removeAll(toRemove);
        masterTable.clearSelection();
        masterTable.setRowSelectionInterval(index, index);
    }//GEN-LAST:event_deleteDetailButtonActionPerformed
    
    private void newDetailButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newDetailButtonActionPerformed
        int index = masterTable.getSelectedRow();
        model.Customer c = list.get(masterTable.convertRowIndexToModel(index));
        Collection<model.Vehicle> vs = c.getVehicleList();
        if (vs == null) {
            vs = new LinkedList<model.Vehicle>();
            c.setVehicleList((List) vs);
        }
        model.Vehicle v = new model.Vehicle();
        entityManager.persist(v);
        v.setCustId(c);
        vs.add(v);
        masterTable.clearSelection();
        masterTable.setRowSelectionInterval(index, index);
        int row = vs.size() - 1;
        detailTable.setRowSelectionInterval(row, row);
        detailTable.scrollRectToVisible(detailTable.getCellRect(row, 0, true));
    }//GEN-LAST:event_newDetailButtonActionPerformed
    

           
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton4ActionPerformed

    private void newDetailButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newDetailButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_newDetailButton1ActionPerformed

    private void deleteDetailButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteDetailButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_deleteDetailButton1ActionPerformed

    private void refreshButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_refreshButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton7ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteDetailButton;
    private javax.swing.JButton deleteDetailButton1;
    private javax.swing.JScrollPane detailScrollPane;
    private javax.swing.JTable detailTable;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLayeredPane jLayeredPane8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private java.util.List<model.Customer> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newDetailButton;
    private javax.swing.JButton newDetailButton1;
    private javax.persistence.Query query;
    private javax.swing.JButton refreshButton1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    public static void main(String[] args) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewMasterDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewMasterDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewMasterDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewMasterDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new NewMasterDetailForm());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
